import geojson
from pyproj import Proj, transform

def wgs84_to_gcj02(coordinates):
    # WGS84坐标系
    wgs84 = Proj(init='epsg:4326')

    # GCJ02坐标系
    gcj02 = Proj(init='epsg:4479')  # 使用高德地图的GCJ02坐标系

    try:
        # 转换坐标点
        return [transform(wgs84, gcj02, coord[0], coord[1]) for coord in coordinates]
    except Exception as e:
        print(f"Error during coordinate transformation: {e}")
        return None

def wgs84_geojson_to_gcj02(geojson_file, output_geojson_file):
    with open(geojson_file, 'r') as f:
        data = geojson.load(f)

        # 转换坐标点
    for feature in data['features']:
        if feature['geometry']['type'] == 'Polygon':
            transformed_coordinates = wgs84_to_gcj02(feature['geometry']['coordinates'])
            if transformed_coordinates:
                feature['geometry']['coordinates'] = transformed_coordinates
        elif feature['geometry']['type'] == 'MultiPolygon':
            transformed_polygons = [wgs84_to_gcj02(polygon) for polygon in feature['geometry']['coordinates']]
            if all(transformed_polygons):
                feature['geometry']['coordinates'] = transformed_polygons

    # 写入转换后的GeoJSON文件
    with open(output_geojson_file, 'w') as f:
        geojson.dump(data, f)

# 使用示例
wgs84_geojson_to_gcj02("D:\Lenovo\Desktop\云南大学\开源地理信息系统\Code\homework3\json\YunnanUniversity_Json.json","D:\Lenovo\Desktop\云南大学\开源地理信息系统\Code\homework3\json\YunnanUniversity_GCJ02.json")
